<template>
  <div class="mapPosition">
    <p style="margin: 0;height: 20px;line-height: 20px;" v-if="positionInfo">当前地址：{{ positionInfo.addr }}</p>
    <el-card class="mapCard">
      <div id="container"></div>
      <div id="myPageTop">
        <table>
          <tr>
            <td>
              <label>请输入关键字：</label>
            </td>
          </tr>
          <tr>
            <td>
              <input id="tipinput"/>
            </td>
          </tr>
        </table>
      </div>
    </el-card>
  </div>
</template>
<script>

export default {
  name: 'Vuemap',
  props: {
    position: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      map: null,
      placeSearch: null,
      positionInfo: null,
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      this.map = new AMap.Map('container', {
        zoom: 15,
        resizeEnable: true
      });//这里是要获取地图容器的id,所以要写在mounted之中

      let that = this;

      //地址实例化
      if (this.position) {
        this.positionInfo = this.position;
        this.addMarker();
      } else { //定位
        this.getGeolocation();
      }

      //点击选择地址
      AMap.event.addListener(this.map, 'click', function (e) { //注册监听，添加地图点击事件
        that.getAddress(e.lnglat, true);
      })

      // 输入提示搜索poi
      let autoOptions = {
        input: 'tipinput'
      }
      let auto = new AMap.Autocomplete(autoOptions)
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map
      })
      AMap.event.addListener(auto, "select", this.select);//注册监听，当选中某条记录时会触发
      AMap.event.addListener(this.placeSearch, 'markerClick', function (e) {
        that.getAddress(e.data.location, false);
      });//注册监听，选中点标记时触发
    },
    //定位
    getGeolocation() {
      let geolocation
      let that = this
      const options = {
        enableHighAccuracy: true, // 是否使用高精度定位，默认:true
        timeout: 10000,           // 超过10秒后停止定位，默认：无穷大
        maximumAge: 0,            // 定位结果缓存0毫秒，默认：0
        convert: true,            // 自动偏移坐标，偏移后的坐标为高德坐标，默认：true
        showButton: true,         // 显示定位按钮，默认：true
        buttonPosition: 'RB',     // 定位按钮停靠位置，默认：'LB'，左下角
        buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        showMarker: true,         // 定位成功后在定位到的位置显示点标记，默认：true
        showCircle: true,         // 定位成功后用圆圈表示定位精度范围，默认：true
        panToLocation: true,      // 定位成功后将定位到的位置作为地图中心点，默认：true
        zoomToAccuracy: true       // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
      }
      AMap.plugin(['AMap.Geolocation'], function () {
        geolocation = new AMap.Geolocation(options)
        that.map.addControl(geolocation)
        geolocation.getCurrentPosition()
      })
      AMap.event.addListener(geolocation, 'complete', this.onComplete); // 返回定位信息
      AMap.event.addListener(geolocation, 'error', this.onError);       // 返回定位出错信息
    },
    onComplete(obj) {
      this.positionInfo = {
        lng: obj.position.lng,
        lat: obj.position.lat,
        addr: obj.formattedAddress
      }
    },
    onError(obj) {
      alert(obj.info + '--' + obj.message);
    },
    select(e) {
      this.map.clearMap();//删除地图上所有的覆盖物
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name);  //关键字查询查询
    },
    markerClick(e) {
      let formattedAddress = e.data.pname + e.data.cityname + e.data.adname + e.data.address + e.data.name;
      this.positionInfo = {
        lng: e.data.location.lng,
        lat: e.data.location.lat,
        addr: formattedAddress
      }
    },
    // 经纬度转化为详细地址
    getAddress(lnglat, sta) {
      let that = this;
      AMap.plugin('AMap.Geocoder', function () {
        let geocoder = new AMap.Geocoder({
          radius: 50,
          extensions: "base"
        });
        geocoder.getAddress([lnglat.lng, lnglat.lat], function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            that.positionInfo = {
              lng: lnglat.lng,
              lat: lnglat.lat,
              addr: result.regeocode.formattedAddress
            }
            if (sta) that.addMarker();
          }
        });
      })
    },
    // 实例化点标记
    addMarker() {
      this.map.clearMap();//删除地图上所有的覆盖物
      let lnglat = [this.positionInfo.lng, this.positionInfo.lat];
      let marker = new AMap.Marker({
        map: this.map,
        position: lnglat,
        icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
      });
      this.map.setCenter(lnglat);
    },
    //选择地址返回
    changeSelectBack() {
      this.$emit("selectAddrBack", this.positionInfo);
    }
  }
}
</script>
<style scoped>
.mapPosition {
  width: 100%;
  height: 100%;
  position: relative;
}

.mapCard >>> .el-card__body {
  padding: 0;
}

#container {
  width: 100%;
  height: 400px;
  margin: 0 auto;
}

#myPageTop {
  position: absolute;
  top: 30px;
  right: 10px;
  background: #fff;
  border: 1px #ccc solid;
  border-radius: 5px;
  padding: 5px;
}

#tipinput {
  width: 200px;
}

.mapCard >>> .amap-icon img,
.mapCard >>> .amap-marker-content img {
  width: 28px;
  height: 40px;
}
</style>
